/*  
 *  ------ [802_04a] - send packets using a unicast 16-bit address -------- 
 *  
 *  Explanation: This program shows how to send packets with 
 *  XBee-802.15.4 modules. The destination address is set as a
 *  16-bit network address 
 *  
 *  Copyright (C) 2012 Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details. 
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 *  
 *  Version:           0.1 
 *  Design:            David Gascón 
 *  Implementation:    Yuri Carmona
 */
 
#include <MakeSureXBee802.h>
#include <MakeSureFrame.h>

// create packet to send
packetXBee* packet;

// Destination MAC address
char* MAC_ADDRESS="0013A200405C3AE7";
char* MAC_LOW="405C3AE7";
char* MoteID="MakeSure_XBEE";
String s;
void setup()
{  
  // init USB port
 // USB.ON();
  //USB.println(F("802_04a example"));
	Serial.begin(9600);
	Serial.write("802_04a example");
  // init XBee 
  xbee802.ON();
  
  // set 0x1212 as (MY) Network Address
  xbee802.setOwnNetAddress(0x12,0x12);
  
  // write values to XBee module memory
  xbee802.writeValues(); 
    
}



void loop()
{  
  ///////////////////////////////////////
  // 1. Create Data Frame
  ///////////////////////////////////////

  // 1.1 create new frame
  //frame.createFrame(ASCII, "MakeSure_XBEE");  
  //
  //// 1.2 add frame fields
  //frame.addSensor(SENSOR_STR, "This is a message");  
  
	frame.createFrame(ASCII,MAC_LOW,MoteID);  
 Serial.println("Frame Created");
  // add frame fields
  frame.addSensor(SENSOR_STR, "XBee frame");
  Serial.println("Added Sensor");
  //frame.addSensor(SENSOR_BAT, PWR.getBatteryLevel()); 
    
  ///////////////////////////////////////
  // 2. Send packet
  ///////////////////////////////////////
    
  // 2.1 set packet parameters:
  packet=(packetXBee*) calloc(1,sizeof(packetXBee)); // memory allocation
  packet->mode=UNICAST; // set Unicast mode
  
  // 2.2 sets Destination parameters
  xbee802.setDestinationParams(packet, "1212", frame.buffer, frame.length, MY_TYPE); 
  
  // 2.3 send data
  xbee802.sendXBee(packet);
  s=String(packet->data);
  Serial.println(s);
  // 2.4 check TX flag
  if( xbee802.error_TX == 0) 
  {
    Serial.println("ok");
  }
  else 
  {
    Serial.println("error");
  }
  
  // 2.5 free memory
  free(packet);
  packet=NULL; 
  
  
  delay(3000);

} 
